package com.app.micaihu.view.user.userinfo.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.Window
import android.widget.TextView
import com.app.base.BaseMvpActivity
import com.app.http.bean.BaseBean
import com.app.micaihu.R
import com.app.micaihu.app.AppApplication
import com.app.micaihu.base.bean.DataBean
import com.app.micaihu.bean.infor.UploadFileResult
import com.app.micaihu.bean.infor.UserInfor
import com.app.micaihu.bean.infor.UserTask
import com.app.micaihu.configure.Config
import com.app.micaihu.configure.TypeConstant
import com.app.micaihu.configure.URIContant
import com.app.micaihu.manager.UserInforManager
import com.app.micaihu.utils.DialogUtils
import com.app.micaihu.utils.OkHttp3Helper
import com.app.micaihu.utils.OkHttp3Helper.OnUploadResponseCallBack
import com.app.micaihu.view.login.ChangePassActivity
import com.app.micaihu.view.login.ChangePhoneActivity
import com.app.micaihu.view.login.activity.BindPhoneActivity
import com.app.micaihu.view.login.contract.LogInContract
import com.app.micaihu.view.login.presenter.LogInPresenter
import com.app.micaihu.view.main.view.GlideEngine
import com.app.micaihu.view.utils.loadCircleImage
import com.app.utils.util.GsonUtils
import com.app.utils.util.ToastUtils
import com.app.utils.util.file.AppFileUtils
import com.app.utils.util.image.LoadImageUtils
import com.blankj.utilcode.util.*
import com.google.gson.reflect.TypeToken
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA
import kotlinx.android.synthetic.main.activity_userinfor.*
import okhttp3.Response
import java.io.File
import java.util.*

/**
 * Created by Guo on 2016/7/13.
 * 个人中心
 */
class UserInforActivity : BaseMvpActivity<LogInContract.View, LogInPresenter>(), LogInContract.View, View.OnClickListener {
    private var userInfor: UserInfor? = null
    private var userTask: UserTask? = null
    private val CHANGE_HEADPIC = 103 //修改头像
    private val UPLOAD_FAIL = 111 //上传失败
    private val NET_ERROR = 122 //网络错误
    private var nickName: String? = ""
    private var changeHeadDialog: Dialog? = null
    private val handler: Handler =
            @SuppressLint("HandlerLeak")
            object : Handler() {
                override fun handleMessage(msg: Message) {
                    when (msg.what) {
                        CHANGE_HEADPIC -> {
                            userInfor?.let {
                                ToastUtils.makeText("修改成功")
                                civ_userinfor_avater.loadCircleImage(it.headPic, R.drawable.task_head_nologging_nor)
                            }
                        }
                        UPLOAD_FAIL -> {
                            ToastUtils.makeText("上传失败，请重新上传...")
                        }
                        NET_ERROR -> ToastUtils.makeText(resources.getString(R.string.neterror))
                    }
                }
            }

    override fun getPresenter() = LogInPresenter()
    private var platform: SHARE_MEDIA? = null
    private val umAuthListener: UMAuthListener = object : UMAuthListener {
        override fun onStart(share_media: SHARE_MEDIA) {
            LogUtils.e(classTag, "platform onStart()$share_media")
        }

        override fun onComplete(share_media: SHARE_MEDIA, i: Int, map: Map<String, String>) {
            LogUtils.e(classTag, "platform onComplete()$share_media  ${map.toString()}")
            var headPic: String? = ""
            var fromType = ""
            var openId: String? = ""
            when (platform) {
                SHARE_MEDIA.QQ -> {
                    nickName = map["screen_name"]
                    headPic = map["profile_image_url"]
                    openId = map["openid"]
                    fromType = TypeConstant.QQ_LOGIN
                }
                SHARE_MEDIA.WEIXIN -> {
                    openId = map["openid"]
                    nickName = map["screen_name"]
                    headPic = map["profile_image_url"]
                    fromType = TypeConstant.WEIXIN_LOGIN
                }
                SHARE_MEDIA.SINA -> {
                    openId = map["id"]
                    nickName = map["screen_name"]
                    headPic = map["cover_image_phone"]
                    fromType = TypeConstant.SINA_LOGIN
                }
                else -> {

                }
            }
            mPresenter?.boundThirdUser(openId, nickName, headPic, fromType)
        }

        override fun onError(share_media: SHARE_MEDIA, i: Int, throwable: Throwable) {
            LogUtils.e(classTag, "platform onError()$share_media  $i   $throwable")
        }

        override fun onCancel(share_media: SHARE_MEDIA, i: Int) {
            LogUtils.e(classTag, "platform onCancel()$share_media  $i  ")
        }
    }

    override fun getLayoutId() = R.layout.activity_userinfor

    override fun setData() {
        getCommonTitle().title = "个人中心"
    }

    override fun addListeners() {
        rl_userhead?.setOnClickListener(this)
        rl_nickname?.setOnClickListener(this)
        rl_level?.setOnClickListener(this)
        rl_rank?.setOnClickListener(this)
        rl_phone?.setOnClickListener(this)
        rl_resetpwd?.setOnClickListener(this)
        ll_signature?.setOnClickListener(this)
        rlMilitary.setOnClickListener {
            userInfor?.let {
                val militaryH5 = it.military_h5 + "?uid=" + it.uid
                val bundle = Bundle()
                bundle.putString(Config.Extra.url, militaryH5)
                enterPager(WebActivity::class.java, bundle)
            }
        }
        tvWxBind.setOnClickListener {
            val api = UMShareAPI.get(thisActivity)
            platform = SHARE_MEDIA.WEIXIN
            val install = api.isInstall(thisActivity, SHARE_MEDIA.WEIXIN) //判断是否本地有客户端
            if (install) {
                api.getPlatformInfo(thisActivity, platform, umAuthListener)
            } else {
                ToastUtils.makeText("请先安装微信客户端")
            }
        }
        tvQQBind.setOnClickListener {
            val api = UMShareAPI.get(thisActivity)
            platform = SHARE_MEDIA.QQ
            val installQQ = api.isInstall(thisActivity, SHARE_MEDIA.QQ) //判断是否本地有客户端
            if (installQQ) {
                api.getPlatformInfo(thisActivity, platform, umAuthListener)
            } else {
                ToastUtils.makeText("请先安装QQ客户端")
            }
        }
        tvSinaBind.setOnClickListener {
            val api = UMShareAPI.get(thisActivity)
            platform = SHARE_MEDIA.SINA
            val install = api.isInstall(thisActivity, SHARE_MEDIA.SINA) //判断是否本地有客户端
            if (install) {
                api.getPlatformInfo(thisActivity, platform, umAuthListener)
            } else {
                ToastUtils.makeText("请先安装微博客户端")
            }
        }
    }

    override fun onResume() {
        super.onResume()
        initViewData()
    }

    /**
     * 加载一些用户数据
     */
    private fun initViewData() {
        UserInforManager.getInstance().userInfor?.let { userInfo ->
            userInfor = userInfo
            civ_userinfor_avater.loadCircleImage(userInfo.headPic, R.drawable.task_head_nologging_nor)
            tv_nickname.text = userInfo.getNickName()
            tv_signaturestr.text =
                    if (TextUtils.isEmpty(userInfo.getSignature()))
                        resources.getString(R.string.user_signature_empty)
                    else
                        userInfo.getSignature()

            if (!TextUtils.isEmpty(userInfo.mobile)) { //已绑定,并且当前用户有手机号
                tv_phonenum.setTextColor(ColorUtils.getColor(R.color.userinfor_text_color))
                tv_phonenum.text = UserInforManager.getInstance().jiamiPhone
                rl_resetpwd?.visibility = View.VISIBLE
            } else {
                tv_phonenum?.setTextColor(resources.getColor(R.color.app_theme))
                tv_phonenum?.text = "绑定手机号"
                rl_resetpwd?.visibility = View.GONE
            }
            val typeIndex = userInfo.militaryType.toInt()
            if (typeIndex > 0 && typeIndex <= Config.militaryList.size) {
                tvMilitary.text = Config.militaryList[typeIndex - 1]  // 军种
            }
            setBindData(userInfo)
            userInfo.task?.let {
                userTask = it
                tv_level.text = it.level
                LoadImageUtils.getInstance().loadImage(civ_rankicon, it.getRankIcon())
                tv_rankname?.text = it.getRankName()
                tv_militaryexploit?.text = it.getMilitaryExploit()
                tv_militarypay?.text = it.getMilitarPay()
            }
            tv_signaturestr?.post {
                if (tv_signaturestr?.layoutParams != null) {
                    if (tv_signaturestr?.lineCount == 1) {
                        tv_signaturestr?.gravity = Gravity.RIGHT
                    } else if (tv_signaturestr?.lineCount == 2) {
                        tv_signaturestr?.gravity = Gravity.LEFT
                    }
                }

            }
        }

    }

    private fun setBindData(userInfo: UserInfor) {
        userInfo.boundStatus?.let {
            if (it.wechat.isNullOrEmpty()) {
                tvWxBind.visibility = View.VISIBLE
            } else {
                tvWxBind.visibility = View.INVISIBLE
                tvWxName.text = "已绑定 ${it.wechat}"
            }

            if (it.qq.isNullOrEmpty()) {
                tvQQBind.visibility = View.VISIBLE
            } else {
                tvQQBind.visibility = View.INVISIBLE
                tvQQName.text = "已绑定 ${it.qq}"
            }

            if (it.weibo.isNullOrEmpty()) {
                tvSinaBind.visibility = View.VISIBLE
            } else {
                tvSinaBind.visibility = View.INVISIBLE
                tvSinaName.text = "已绑定 ${it.weibo}"
            }

        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.rl_userhead -> showThreeDialog()
            R.id.rl_nickname -> {
                val intentNickName = Intent(this, EditorUserInfoActivity::class.java)
                intentNickName.putExtra(Config.Extra.PARAMETER1, "昵称")
                intentNickName.putExtra(Config.Extra.PARAMETER2, "1")
                startActivity(intentNickName)
            }
            R.id.ll_signature -> {
                val intentSignature = Intent(this, EditorUserInfoActivity::class.java)
                intentSignature.putExtra(Config.Extra.PARAMETER1, "个性签名")
                intentSignature.putExtra(Config.Extra.PARAMETER2, "2")
                startActivity(intentSignature)
            }
            R.id.rl_level, R.id.rl_rank -> UserInforManager.getInstance().toWebActivity(this@UserInforActivity, "军衔等级", URIContant.MILITARY_RANK + "?uid=" + UserInforManager.getInstance().userInfor.uid)
            R.id.rl_phone -> {
                val userInfor = UserInforManager.getInstance().userInfor
                if (userInfor != null && !StringUtils.isEmpty(userInfor.mobile)) {
                    startActivityForResult(Intent(this, ChangePhoneActivity::class.java), Config.ResultCode.REQUESTCODE_1)
                } else {
                    startActivityForResult(Intent(this, BindPhoneActivity::class.java), Config.ResultCode.REQUESTCODE_1)
                }
            }
            R.id.rl_resetpwd -> if (!ActivityUtils.isActivityExistsInStack(ChangePassActivity::class.java)) {
                startActivityForResult(Intent(this, ChangePassActivity::class.java), Config.ResultCode.REQUESTCODE_1)
            }
        }
    }


    /**
     * 从底部弹出的选择头像的dialog
     */
    private fun showThreeDialog() {
        if (changeHeadDialog == null) {
            val view = LayoutInflater.from(this).inflate(R.layout.dialog_head1, null)
            val tvTop = view.findViewById<View>(R.id.tv_top) as TextView
            val tvBottom = view.findViewById<View>(R.id.tv_bottom) as TextView
            val tvHead = view.findViewById<View>(R.id.tv_apphead) as TextView
            val tvCancel = view.findViewById<View>(R.id.tv_cancel) as TextView
            val onClickListener = View.OnClickListener { v ->
                if (v == null) return@OnClickListener
                if (changeHeadDialog != null) {
                    changeHeadDialog?.dismiss()
                }
                when (v.id) {
                    R.id.tv_top -> {
                        EasyPhotos.createCamera(this)
                                .setFileProviderAuthority(Config.fileProvider)
                                .start(Config.ResultCode.resultCodePhoto)
                    }
                    R.id.tv_bottom -> {
                        //打开相册
                        openPhotos()
                    }
                    R.id.tv_apphead -> {
                        //打开虎哥头像
                        val intent = Intent(thisActivity, AvatarActivity::class.java)
                        startActivity(intent)
                    }
                    R.id.tv_cancel -> {
                    }
                }
            }
            tvTop.setOnClickListener(onClickListener)
            tvBottom.setOnClickListener(onClickListener)
            tvHead.setOnClickListener(onClickListener)
            tvCancel.setOnClickListener(onClickListener)
            changeHeadDialog = Dialog(this, R.style.CustomDialogStyle)
            changeHeadDialog?.requestWindowFeature(Window.FEATURE_ACTION_MODE_OVERLAY)
            changeHeadDialog?.window?.setGravity(Gravity.BOTTOM)
            changeHeadDialog?.setCanceledOnTouchOutside(true)
            changeHeadDialog?.setContentView(view)
        }
        if (!isFinishing) {
            try {
                changeHeadDialog?.show()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun openPhotos() {
        KeyboardUtils.hideSoftInput(this)
        EasyPhotos.createAlbum(this, false, GlideEngine.getInstance())
                .setFileProviderAuthority(Config.fileProvider)
                .setCount(1)
                .setPuzzleMenu(false)
                .setCleanMenu(false)
                .start(Config.ResultCode.resultCodePhoto)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
        if (requestCode == Config.ResultCode.REQUESTCODE_1 && resultCode == Activity.RESULT_OK) { //绑定手机回来
            UserInforManager.getInstance().showLevelDialog(this@UserInforActivity)
        }
        data?.let {
            if (requestCode == Config.ResultCode.resultCodePhoto) {
                //返回对象集合：如果你需要了解图片的宽、高、大小、用户是否选中原图选项等信息，可以用这个
                val resultPhotos: ArrayList<Photo> = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS)
                if (resultPhotos.isNotEmpty()) {
                    val intent = Intent(thisContext, UserHeaderCorpActivity::class.java)
                    intent.data = resultPhotos[0].uri
                    startActivityForResult(intent, Config.ResultCode.resultCodeCorp)
                }
            } else if (requestCode == Config.ResultCode.resultCodeCorp) {
                val path = data.getStringExtra(Config.Extra.path)
                path?.let {
                    uploadFile(File(it))
                }
            }
        }
    }

    /**
     * 上传文件
     *
     * @param uploadFile 上传的图片
     */
    private fun uploadFile(uploadFile: File) {
        val paramMap: HashMap<String?, String?> = HashMap()
        paramMap["type"] = TypeConstant.UPLOAD_TYPE1
        paramMap["uid"] = UserInforManager.getInstance().userInfor.uid
        paramMap["filename"] = "filename"
        paramMap["timestamp"] = System.currentTimeMillis().toString() + ""
        OkHttp3Helper.getInstance().uploadAsynFile(URIContant.UP_FILE, uploadFile, paramMap, object : OnUploadResponseCallBack() {
            override fun onStart() {
                super.onStart()
                DialogUtils.getInstance().showProgressDialog(this@UserInforActivity, "正在提交")
            }

            override fun onFailure() {
                super.onFailure()
                DialogUtils.getInstance().dismissProgressDialog()
            }

            override fun onSucess(response: Response) {
                super.onSucess(response)
                DialogUtils.getInstance().dismissProgressDialog()
                try {
                    if (response != null) {
                        val json = response.body?.string()
                        val gson = GsonUtils.getInstance().gson
                        val uploadHeadPic = gson.fromJson<DataBean<UploadFileResult?>>(json, object : TypeToken<DataBean<UploadFileResult?>?>() {}.type)
                        if (uploadHeadPic != null && uploadHeadPic.data != null) {
                            val headPic = uploadHeadPic.data
                            if (userInfor != null) {
                                userInfor?.headPic = headPic?.url
                                UserInforManager.getInstance().saveUserInfor(userInfor)
                            }
                            handler.sendEmptyMessage(CHANGE_HEADPIC)
                        }
                        AppFileUtils.deleteImageFile(AppApplication.getInstance(), uploadFile)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        })
    }

    override fun handleBoundThirdUser(result: BaseBean<UserInfor?>?) {
        if (result == null) {
            com.blankj.utilcode.util.ToastUtils.showShort(getString(R.string.net_error))
        } else {
            if (result.isSuccess()) {
                result.data?.let { userInfo ->
                    UserInforManager.getInstance().userInfor?.let {
                        it.boundStatus = userInfo.boundStatus
                        UserInforManager.getInstance().saveUserInfor(it)
                    }
                    setBindData(userInfo)
                }
            }
            com.blankj.utilcode.util.ToastUtils.showLong(result.msg)
        }
    }
}